<template>
  <div class="home-container" :class="!screenSrc && 'no-data'">
    <div class="screen-project">
      <!-- @onSelect="handleSelect($event)" -->
      <!-- <icon-fonts icon="icon-xiangmu2" class="pro-icon"></icon-fonts> -->
      <chooseProject @onSelect="handleSelectProject($event)"></chooseProject>
    </div>

    <div class="operate-btns">
      <div
        class="back-home"
        v-if="userAccount == 'projectListPage'"
        @click="gotoBack()"
        title="项目列表"
      ></div>
      <div class="system" @click="gotoSystem()" title="进入系统"></div>
      <!-- <div class="close" @click="handleLogout()" title="退出系统"></div> -->
    </div>
    <iframe
      v-if="screenSrc"
      :src="screenSrc"
      frameborder="0"
      style="width:100%;height:100%"
      allowfullscreen
      webkitallowfullscreen
      mozallowfullscreen
      @load="handleLoad()"
    ></iframe>
    <div class="loading-warp">
      <a-spin :spinning="loading" />
    </div>
    <!--  -->
    <div class="empty-container" v-if="!screenSrc && !$route.query.uuid">
      <a-empty />
    </div>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
import { mapActions, mapGetters } from "vuex";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import Vue from "vue";
import chooseProject from "./components/chooseProject";
import { flatTreeData } from "@/utils/util.js";
export default {
  components: {
    chooseProject,
  },
  data() {
    return {
      screenSrc: "",
      loading: true,
      currentProject: {},
    };
  },
  computed: {
    ...mapGetters(["userAccount", "currentProjectCode"]),
  },
  mounted() {
    // let { uuid = "", proCode = "" } = this.$route.query;
    // if (uuid) {
    //   let user_info = JSON.parse(localStorage.getItem("USER_INFO") ?? "{}");
    //   this.screenSrc = `${
    //     process.env.VUE_APP_API_REPORT_BASE_URL
    //   }/view/${uuid}?token=${Vue.ls.get(
    //     ACCESS_TOKEN
    //   )}&proCode=${proCode}&userId=${user_info.uuid}&unique=dpgl`;
    // } else {
    //   this.loading = false;
    //   this.screenSrc = "";
    // }
  },
  methods: {
    ...mapActions(["Logout"]),
    handleLoad() {
      this.loading = false;
    },
    handleSelectProject(ev) {
      this.currentProject = ev;
      this.getScreenId();
    },
    //查询大屏id
    getScreenId() {
      this.loading = true;
      let user_info = JSON.parse(localStorage.getItem("USER_INFO") ?? "{}");
      let code = this.currentProjectCode || this.currentProject.orgCode;
      let { orgName, foreignUuid } = this.currentProject;
      axios
        .post(
          `/report/reportVisual/queryEnabledByTenantUuid`,
          {
            tenantUuid: code,
            userId: user_info.uuid,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { uuid, type, url } = res.data;
          if (type == "1") {
            //人工开发的大屏
            if (url) {
              this.screenSrc = `${url}/?token=${Vue.ls.get(
                ACCESS_TOKEN
              )}&proCode=${code}&userId=${
                user_info.uuid
              }&unique=dpgl&proName=${orgName}&foreignUuid=${foreignUuid}`;
            } else {
              this.loading = false;
              this.screenSrc = "";
              this.refreshPermission(this.currentProject, false);
            }
          } else {
            //地代码平台配置的大屏
            if (uuid) {
              this.screenSrc = `${
                process.env.VUE_APP_API_REPORT_BASE_URL
              }/view/${uuid}?token=${Vue.ls.get(
                ACCESS_TOKEN
              )}&proCode=${code}&userId=${user_info.uuid}&unique=dpgl`;
            } else {
              this.loading = false;
              this.screenSrc = "";
              this.refreshPermission(this.currentProject, false);
            }
          }
          return;
          if (uuid) {
            // this.screenSrc = `${
            //   process.env.VUE_APP_API_REPORT_BASE_URL
            // }/view/${uuid}?token=${Vue.ls.get(
            //   ACCESS_TOKEN
            // )}&proCode=${code}&userId=${user_info.uuid}&unique=dpgl`;
            //
            //     let currentItem = JSON.parse(
            //     localStorage.getItem("CURRENT_PROJECT") ?? "{}"
            //   );
            // &proName=${currentItem.proName ||
            //     currentItem.orgName}
          } else {
            this.loading = false;
            this.screenSrc = "";
            this.refreshPermission(this.currentProject, false);
          }
        })
        .catch((_) => {
          //   this.refreshPermission(this.currentProject, false);
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    gotoBack() {
      this.$router.push({
        path: "/projectHome",
      });
    },

    //进入系统
    gotoSystem() {
      this.refreshPermission(this.currentProject, false);
    },

    //退出登录
    handleLogout() {
      let that = this;
      this.$confirm({
        title: "提示",
        content: "真的要注销登录吗?",
        okText: "确认",
        cancelText: "取消",
        closable: true,
        centered: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk: () => {
          return this.Logout({})
            .then(() => {
              setTimeout(() => {
                this.$router.push({
                  path: "/user/login?type=private",
                });
              }, 16);
            })
            .catch((err) => {
              this.$message.error({
                title: "错误",
                description: err.message,
              });
            });
        },
        onCancel() {},
      });
    },

    //刷新权限/菜单数据
    async refreshPermission(data = {}, toXmdp) {
      let { proCode, orgCode } = data;
      //缓存所选项目
      localStorage.setItem("CURRENT_PROJECT", JSON.stringify(data));
      localStorage.setItem("CURRENT_PROJECT_CODE", proCode || orgCode);
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT: data,
      });
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT_CODE: proCode || orgCode,
      });
      //
      await this.$store.dispatch("getPermissionIdentifyingByRoleId");
      await this.$store
        .dispatch("getUserInForAndButtonPermissions")
        .then(async (res) => {
          const roles = res && res.role;
          //菜单信息
          let menuSource = await this.$store.dispatch("GenerateRoutes", {
            roles,
          });

          //首页信息
          let portalSource = JSON.parse(
            localStorage.getItem("PORTAL_ROUTERS_DATA" ?? "[]")
          );

          //默认获取一级节点菜单
          let flatMenu = flatTreeData(menuSource, "children");
          let firstMenu = flatMenu.find(
            (v) => !v.children || v.children.length == 0
          );

          //是否有大屏权限
          if (toXmdp) {
            //进入大屏
            this.$router.push({
              path: `/largeScreen`,
            });
          } else {
            //没有首页，有菜单
            if (portalSource.length == 0 && menuSource.length != 1) {
              this.$router.push({
                path: firstMenu.fullPath,
              });
            }
            //没有首页，没有菜单
            else if (portalSource.length == 0 && menuSource.length == 1) {
              this.$router.push({
                path: `/whitePage/index`,
              });
            }
            //有首页，有菜单
            else {
              this.$router.push({
                path: "/system/portal/index",
              });
            }
          }
        });
    },
  },
};
</script>

<style lang="less" scoped>
.home-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  &.no-data {
    background: #081835;
  }
  .empty-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /deep/.ant-empty {
      .ant-empty-description {
        color: #cdecff;
      }
    }
  }
  .loading-warp {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .screen-project {
    z-index: 22;
    position: absolute;
    top: 14px;
    left: 38px;
    display: flex;
    align-items: center;
    .pro-icon {
      color: #00ffff;
      margin-right: 8px;
    }
  }

  .operate-btns {
    position: absolute;
    top: 14px;
    right: 38px;
    display: flex;
    align-items: center;
    z-index: 1001;
    .back-home {
      margin-right: 20px;
      width: 18px;
      height: 18px;
      background: url(~@/assets/img/portalEntry/back_home.png);
      background-size: 100% 100%;
      cursor: pointer;
      pointer-events: all;
    }

    .system {
      margin-right: 20px;
      width: 18px;
      height: 18px;
      background: url(~@/assets/img/portalEntry/system.png);
      background-size: 100% 100%;
      cursor: pointer;
      pointer-events: all;
    }
    .close {
      cursor: pointer;
      width: 18px;
      height: 18px;
      background: url(~@/assets/img/portalEntry/clsoe.png);
      background-size: 100% 100%;
      pointer-events: all;
    }
  }
}
</style>
